import PageBody from '@/components/school/pageBody';

const app = getApp();
import diyJson from '@/config/diy.js';
import {mapGetters} from "vuex";
import * as  UserApi from '@/api/member/user.js';
import Dict from '@/components/school/dict';
import {
  getPermisSchool,
  getPermissions,
  setMemberPermits
} from "../../../api/member/user";

export const mixins = {
  components: {
    PageBody, Dict
  }
  , computed: mapGetters(['userInfo', 'schoolId', 'isLogin']), data() {
    return {
      themConfig: diyJson.commonStyle
      , scrollTop: 0
      , showLoading: true
      , datas: []
      , pageBody: {

      }
      , schoolInfo: [] // 当前选到的学校
      , schoolInfos: [] // 权限管理所选的学校
      , openSchoolType: undefined // 选择学校标记-permission=设置用户权限 agent=设置代理学校
      , mapSchoolInfos: {}
      , isReachBottom: false
      , loading: {
        status: 'nomore',
        loadingText: '加载中',
        loadmoreText: '点击加载更多'
        , dataPage: {
          current: 1,
          total: 0,
          pages: 1,
          size: 10,
        }
      }
      , viewItem: {} // 当前学生
      , currentItemPermis: null // 当前点击的权限
      , permissionDatas: []
      , schools: []
      , searchParams: {
        state: null,
        phone: undefined,
        schoolId: undefined
      }
      , searchForm: {
        id: undefined,
        phone: undefined,
        schoolName: undefined
      }
      , dataPage: {
        current: 1,
        pages: 1,
        size: 10,
        total: 0,
      },
      agentForm: {}
    }
  }
  , onLoad() {
    this.dataList({});
    this.getPermissionsData();
    this.getPermisSchoolData();
  }
  , onShow() {
    // this.getSchoolData();
  },
  mounted() {
    this.computeAmountHeight();
  },
  onPullDownRefresh() {
    this.dataList({...this.searchParams});
    uni.stopPullDownRefresh();
  },
  onReachBottom() {
    this.scrolltolower();
  },
  methods: {

    // 切换学校
    switchSchoolTab() {
      uni.navigateTo({
        url: '/pages/school/info/index'
      })
    },

    setSchool(e) {
      if (this.openSchoolType === 'permission') {
        let a = this.schoolInfos.filter(a => a.id === e.id);
        if (a.length <= 0) {
          this.schoolInfos.push(e);
        }
        this.mapSchoolInfos[this.currentItemPermis.code] = this.schoolInfos;
      }

      if (this.openSchoolType === 'agent') {
        let form = {...this.agentForm}
        console.log("form", form)
        form['schoolId'] = e.id;
        form['schoolName'] = e.schoolName;
        this.agentForm = form;
      }

      this.schoolInfo = e;
      console.log("选择学校", e)
    },

    closeSchoolsPermiss(i) {
      this.schoolInfos.splice(i, 1);
      this.mapSchoolInfos[this.currentItemPermis.code] = this.schoolInfos;
    },

    async computeAmountHeight() {
      // const query = uni.createSelectorQuery().in(this);
      // let that = this;
      // query.select('.heightWrapper')
      // .boundingClientRect((dome) => {
      //   console.log("height", dome.height)
      //   that.pageBody['paddingTop'] =  dome.height;
      // })
      // .exec();
    },

    // 获取管理员权限
    getPermissionsData() {
      UserApi.getPermissions().then(res => {
        this.permissionDatas = res.data;
      })
    },

    // 获取管理员权限
    getPermisSchoolData() {
      UserApi.getPermisSchool().then(res => {
        let arr = [{name: '清空', id: ''}];
        res.data.forEach(item => {
          arr.push({name: item.schoolName, id: item.id})
        })
        this.schools = arr;
      })
    },

    // 打开搜索
    filterCondition() {
      this.$refs.popup.open();
    },

    // 图片放大
    imgOpenLager(e) {
      uni.previewImage({
        urls: [e], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
        current: '', // 当前显示图片的http链接，默认是第一个
        success: function (res) {
        },
        fail: function (res) {
        },
        complete: function (res) {
        },
      })
    },

    // 状态切换
    tabListChange(e) {
      this.searchParams.state = e.value
      this.loading.status = 'nomore';
      this.dataList({...this.searchParams});
    },
    // 滚到底部
    scrolltolower() {
      this.isReachBottom = true;
      this.loading.status = 'nomore';
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loadmore';
      }
    },
    loadmore() {
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loading';
        UserApi.pages(
            {...this.searchParams, current: this.dataPage.current + 1}).then(
            res => {
              res.data.records.forEach(item => {
                this.datas.push(item)
              })
              this.dataPage.current = res.data.current;
              this.dataPage.pages = res.data.pages;
              this.loading.status = 'loadmore';
            })
      }
    },
    refreshList() {
      this.dataList({...this.searchParams});
    },

    dataList(params) {
      if (this.datas.length > 0) {
        this.datas.splice(0, 1);
      }
      UserApi.pages(params).then(res => {
        this.datas = res.data.records;
        this.dataPage.current = res.data.current;
        this.dataPage.total = res.data.total;
        this.dataPage.pages = res.data.pages;
      })
    },
    submit(pass, item) {

    },

    // 打开权限管理
    openPermissionManager(item) {
      this.viewItem = item;
      this.$refs.permission_popup.open();
      this.openSchoolType = 'permission';
    },

    openAgentManager(item) {
      this.viewItem = item;

      // 初始化
      this.agentForm = item.agentInfo || {};
      this.agentForm['memberId'] = item.id;
      this.agentForm['isAgent'] = item.isAgent;
      if (item.agentInfo === null) {
        this.agentForm['schoolId'] = '';
        this.agentForm['schoolName'] = '';
      }

      console.log("openAgentManager", this.agentForm)

      this.$refs.agent_popup.open();
      this.openSchoolType = 'agent';
    },

    // 给用户添加权限
    addPermisions(it) {
      this.currentItemPermis = it;

      console.log("当前权限", it)
      let sch = this.mapSchoolInfos[it.code];
      if (sch === undefined || sch === null) {
        sch = [];
      }

      // 去重复
      let exitSchool = [];
      console.log("sch", sch)
      sch.forEach(sc => {
        exitSchool.push(sc.id);
      })

      // 当前用户的权限学校 回显
      if (!this.viewItem.permissions) {
        this.viewItem.permissions = []
      }
      this.viewItem.permissions.forEach(uIt => {
        if (it.code === uIt.code) {
          uIt.schoolInfos.forEach(a => {
            if (exitSchool.indexOf(a.schoolId) < 0) {
              a['id'] = a.schoolId;
              sch.push(a)
            }
          })
        }
      })

      this.schoolInfos = sch;
      this.mapSchoolInfos[it.code] = sch;

      let arr = this.viewItem.permissions;
      let tempExitArr = arr.filter(a => a.code === it.code);
      if (tempExitArr.length <= 0) {
        this.viewItem.permissions.push(it);
      }
    },

    // 关闭用户权限标签
    closeMemberPermiss(idx) {
      console.log("关闭用户权限标签", idx);

      let item = this.viewItem.permissions[idx];
      if (this.currentItemPermis != null) {
        if (item.code === this.currentItemPermis.code) {
          this.currentItemPermis = null;
        }
      }

      delete this.mapSchoolInfos[item.code];

      this.viewItem.permissions.splice(idx, 1);
    },

    // 提交保存用户权限
    submitPermission() {
      let permis = this.viewItem.permissions;
      let that = this;
      permis.forEach(it => {
        let schools = that.mapSchoolInfos[it.code];
        let schoolItem = schools == null ? [] : schools;

        let schoolIds = [];
        schoolItem.forEach(s => {
          schoolIds.push(s.id);
        });
        it.schoolIds = schoolIds;
      })
      let form = {
        memberId: this.viewItem.id,
        permisList: this.viewItem.permissions
      }
      UserApi.setMemberPermits(form).then(res => {
        this.$refs.permission_popup.close();
        this.dataList({...this.searchParams})
      })
    },

    // 选择学校
    openSchool() {
      this.$refs.actionSheet.open();
    },
    // 获取搜索学校列表
    getSchoolData() {
      UserApi.getSchools().then(res => {
        let arr = [{name: '清空', id: ''}];
        res.data.forEach(item => {
          arr.push({name: item.schoolName, id: item.id})
        })
        this.schools = arr;
      })
    },
    // 选择学校
    selectSchool(e) {
      if (e.name === '清空') {
        delete this.searchParams['schoolId'];
        this.searchForm.schoolName = undefined;
      } else {
        this.searchForm.schoolName = e.name;
        this.searchParams['schoolId'] = e.id;
      }
      this.$refs.actionSheet.close();
    },
    clearForm() {
      this.searchForm = {
        id: undefined,
        phone: undefined,
        schoolName: undefined
      }
      this.dataList({});
    },
    submitSearchForm() {
      let form = {...this.formData, ...this.searchParams, ...this.searchForm};
      delete form['schoolName'];
      this.dataList(form);
      this.$refs.popup.close();
    },

    // 代理设置--------------------------
    closeAgentForm() {
      this.$refs.agent_popup.close();
    },
    submitAgent() {
      UserApi.setAgent(this.agentForm).then(res => {
        this.dataList({...this.searchParams})
        this.$refs.agent_popup.close();
      })
    }

  }
}
